package com.ebupt.migu.music.common.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.Cursor;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileWriter;

@Slf4j
@Service
public class ExportFileDataFromRedis {

    @Value("${sftp.local_path}")
    private String LOCAL_PATH;

    /**
     * 文件导出
     *
     * @param cursor
     * @param fileName
     * @return
     */
    @Async
    public void export(Cursor<String> cursor, String fileName) {
        exportFile(cursor, fileName);
    }

    /**
     * 通知tsg获取文件时必须同步执行<br>
     * 同步文件导出
     *
     * @param cursor redis中key值游标
     * @param fileName 文件名
     */
    public void syncExport(Cursor<String> cursor, String fileName) {
        exportFile(cursor, fileName);
    }

    private void exportFile(Cursor<String> cursor, String fileName) {
        String path = LOCAL_PATH + fileName;
        log.info("开始生成明细文件：{}", path);
        File file = new File(path);
        FileWriter fileWriter = null;
        try {
            fileWriter = new FileWriter(file, true);
            while (cursor.hasNext()) {
                String data = cursor.next();
                fileWriter.write(data);
                fileWriter.write("\r\n");
            }
            fileWriter.close();
            log.info("明细导出完成：{}", fileName);
        } catch (Exception e) {
            log.error("从redis中导出明细数据失败：{}", fileName);
        }
    }
}
